package com.sghd.fight.module.game.service.work;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class RoomThread extends Thread {
    private static Logger logger = LoggerFactory.getLogger(RoomThread.class);

    private int index;

    private BlockingQueue<RoomWork> works = new LinkedBlockingQueue<>();

    private volatile boolean run = true;

    public RoomThread(int index) {
        super("RoomThread[" + index + "]");
        this.index = index;
    }

    public RoomThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        while (run) {
            RoomWork work;
            try {
                work = works.take();
                work.getContent().run(work.getEnd());
            } catch (InterruptedException e) {
                logger.error("任务线程[{}]被打断", getName(), e);
            } catch (Throwable e) {
                logger.error("任务线程[{}]发生未知错误", getName(), e);
            }
        }
    }

    public void stopWork() {
        run = false;
    }

    public void addWork(RoomWork work) {
        works.add(work);
    }

    public int getIndex() {
        return index;
    }

    public int size() {
        return works.size();
    }

    public boolean remove(RoomWork work) {
        return works.remove(work);
    }

}